﻿using System;
using System.Web;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using WAD.DAL;
using WAD.WEB.AppCode;
using GlTool.GlHttp;
using GL.Tools;
using WAD.Model.JSON.Oauth;
using WAD.Model;

namespace WAD.Client2.OAuth
{
    /// <summary>
    /// QQLogin2 的摘要说明
    /// </summary>
    public class QQLogin : AjaxBase
    {
        public override void AjaxMethodDispatch(String identity)
        {
            switch (identity)
            {
                case "login": this.Login(); break;
            }
        }
        string code = ""; //返回的Code
        protected override void PageLoad()
        {
            base.PageLoad();
            code = Parse.String("code");
            if (Request.QueryString.Count > 0 && Request.QueryString[0] == "login") { }
            else CallBack();
        }

        [QD.Web.Ajax.AjaxMethod]
        public void Login()
        {
            //第一步： 获取code
            string url = string.Format("https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id={0}&redirect_uri={1}&state={2}", QQLoginConfig.APPID, QQLoginConfig.Redirect_Uri, CreateState());
            Response.Redirect(url);
        }

        void CallBack()
        {
            if (string.IsNullOrEmpty(code))
            {
                //JsonResult(500, "授权失败！code参数无效");
                Response.Redirect("/client/personal.html");
            }

            MUser model = OAuth();

            //Response.Write("昵称：" + model.nick_name);
            //Response.Write("<br>头像：" + model.logo);
            //Response.Write("<br>登录类型：" + model.api_rs);
            //return;
            if (model != null)
                UserLogin(model);               //验证成功后，注册用户、登录
        }

        MUser OAuth()
        {
            string state = Parse.String("state", "");
            //第二步：通过 Code 获取Access Token
            string url2 = "https://graph.qq.com/oauth2.0/token?";
            string query = string.Format("grant_type=authorization_code&code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&state={4}", code, QQLoginConfig.APPID, QQLoginConfig.APPKEY, QQLoginConfig.Redirect_Uri, state);
            string html = GetHtml(url2 + query);

            if (html.IndexOf("access_token") == -1)
                JsonResult(500, "授权失败!无法获取access_token,返回码: " + html);

            string access_token = GetToken(html);

            //第三步:通过 Access Token 获取OpenID
            string url3 = string.Format("https://graph.qq.com/oauth2.0/me?access_token={0}", access_token);
            html = GetHtml(url3);

            MQQLogin json = JsonParse<MQQLogin>(Format(html.Trim()));
            string openid = json.OpenID;

            if (json == null || string.IsNullOrEmpty(json.OpenID))
                JsonResult(500, "授权失败!无法获取openid,返回码: " + html);

            //第四步： 获取用户头像、昵称
            string url4 = string.Format("https://graph.qq.com/user/get_user_info?access_token={0}&oauth_consumer_key={1}&openid={2}", access_token, QQLoginConfig.APPID, json.OpenID);
            html = GetHtml(url4);

            json = JsonParse<MQQLogin>(Format(html.Trim()));
            json.OpenID = openid;
            if (json == null || string.IsNullOrEmpty(json.Ret))
                JsonResult(500, "授权失败!无法获取用户昵称、头像,返回码: " + html);

            return GetModel(json);
        }

        void UserLogin(MUser model)
        {
            //登陆数据
            Dictionary<String, object> data = null;
            int code = DaoUser.Login(model, out data);
            switch (code)
            {
                case Message.Code.ERROR_NAME:
                    Register(model);    //注册新账号
                    break;
                case Message.Code.ERROR_PWD:
                    JsonResult(Message.Code.ERROR_PWD, Message.Msg.ERROR_PWD);
                    break;
                case Message.Code.ERROR_STATE:
                    GoHome(Message.Code.ERROR_STATE, Message.Msg.ERROR_STATE, null);
                    break;
                case Message.Code.SUCCESS:
                    GoHome(code, "", data);
                    break;
            }
        }

        void Register(MUser model)
        {
            int code = DaoUser.Regist(model);
            if (code != Message.Code.SUCCESS)
                GoHome(500, "账号同步失败，请重试", null);

            Dictionary<String, object> data = null;
            code = DaoUser.Login(model, out data);

            if (code != Message.Code.SUCCESS)
                GoHome(500, "登录出现了问题，请重试", null);
            GoHome(0, "", data);
        }


        string CreateState()
        {
            return Guid.NewGuid().ToString("N");
        }

        MUser GetModel(MQQLogin json)
        {
            Random rand = new Random();
            MUser model = new MUser();
            model.name = "wx" + rand.Next(10000000, 99999999);
            model.nick_name = json.NickName;
            model.logo = json.FigureUrl_QQ_2;   //头像,完整URL
            model.login_type = 2;           //1 账号密码登录，2 QQ登录，3微信登录
            model.phone = "";
            model.pwd = "";
            model.qq = "";
            model.email = "";
            model.api_rs = json.OpenID;
            if (Request.Cookies["a"] != null)
            {
                if (!string.IsNullOrEmpty(Request.Cookies["a"].Value))
                    model.agentid = Convert.ToInt32(Request.Cookies["a"].Value);    //推荐人ID
            }
            return model;
        }

        string GetToken(string html)
        {
            string token = "";
            string[] arr = html.Split('&');
            for (int i = 0; i < arr.Length; i++)
            {
                string[] item = arr[i].Split('=');
                if (item != null && item.Length == 2)
                {
                    if (item[0].IndexOf("access_token") > -1)
                        token = item[1];
                }
            }
            return token;
        }

        string Format(string html)
        {
            Regex r1 = new Regex(@"^callback\(([\s\S]+)\);");
            if (r1.IsMatch(html))
                return r1.Match(html).Groups[1].Value;
            return html;
        }

        void GoHome(int code, string msg, Dictionary<string, object> data)
        {
            string param = string.Format("?action=oauth&code={0}&msg={1}", code, msg);
            if (data != null)
            {
                Dictionary<string, object>.Enumerator ie = data.GetEnumerator();
                while (ie.MoveNext())
                {
                    if (ie.Current.Key.Equals("id"))
                        param += "&user_id=" + ie.Current.Value;
                    if (ie.Current.Key.Equals("token"))
                        param += "&token=" + ie.Current.Value;
                }
            }
            Response.Redirect(WJXConfig.Path.LoginUrl2 + param);
        }

        string GetHtml(String url)
        {
            GlHttpGet httpGet = new GlHttpGet(url);

            //设置浏览器标识
            httpGet.setHead("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36");

            GlHttpResponse response = httpGet.Execute();
            if (response == null)
            {
                return null;
            }
            return response.ToString();
        }
    }
}